<!--  -->
<template>
  <div class="setting-container">
    <el-card>
      <div slot="header">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 表单 -->
      <el-row>
        <el-col :span="16">
          <el-form
            ref="user"
            :model="user"
            label-width="80px"
          >
            <el-form-item label="手机">
              {{user.mobile}}
            </el-form-item>
            <el-form-item label="作者名称">
              <el-input v-model="user.name"></el-input>
            </el-form-item>
            <el-form-item label="作者个签">
              <el-input
                type="textarea"
                v-model="user.intro"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="user.email"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button
              style="width:150px"
                type="primary"
                @click="onUpdataUser"
                :loading='updataProfileLoading'
              >保存</el-button>
              <el-button v-if="false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <!-- offset位置 -->
        <el-col
          :offset="2"
          :span="4"
        >

          <!-- 第一种方法 -->
          <!-- <p @click="$refs.file.click()">点击修改头像</p>
          <input type="file"
                 hidden
                 ref="file"> -->
          <!-- 第二种方法 -->
          <!-- <label for="file">点击修改头像</label>
          <input id="file"
                 type="file"
                 hidden
                 ref="file"> -->
          <label for="file">
            <!-- <el-avatar shape="square"
                       :size="150"
                       fit="cover"
                       :src="this.user.photo.length===14?('http://1.15.144.141:8081/uploads/'+this.user.photo):this.user.photo"></el-avatar> -->
            <!-- <el-avatar shape="square"
                       :size="150"
                       fit="contain"
                       class="imagees"
                       :src="this.user.photo.length===25?(this.baseURL+'/uploads/'+this.user.photo):this.user.photo"></el-avatar> -->
            <div class="imgBox">
              <el-image
                style="height: 100%; width:100%"
                :src="images()"
                fit="contain"
              ></el-image>
            </div>
          </label>
          <input
            id="file"
            type="file"
            ref="file"
            hidden
            @change="onFileChange"
          >
        </el-col>
      </el-row>
    </el-card>
    <!-- 选择图片提示 -->
    <el-dialog
      title="修改头像"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      append-to-body
      :show-close="!uploadPhotoLoading"
      @opened="onDialogOpen"
      @closed="onDialogClose"
    >
      <div class="preview-image-wrap">
        <img
          class="preview-image"
          :src="priviewImage"
          ref="preview-image"
          alt=""
          id="image"
        >
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="uploadPhotoLoading"
          @click="onUpdataPhoto"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserProfile, updataUserPhoto, upadataUserprofile } from '@/api/user'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import gloobalBus from '@/utils/global-bus'
import readFileImg from '@/utils/image-compress' // 图片压缩

export default {
  name: 'SettingIndex',
  components: {},
  props: {},
  data () {
    return {
      baseURL: this.baseURL,
      user: {
        email: '',
        intro: '',
        id: null,
        name: '',
        mobile: '',
        photo: ''
      },
      photo: '',
      dialogVisible: false,
      priviewImage: '',
      cropper: null,
      uploadPhotoLoading: false,
      updataProfileLoading: false
    }
  },
  computed: {
    images: function () {
      return function () {
        const img =
          this.user?.photo?.length > 25
            ? this.user?.photo
            : this.baseURL + '/uploads/' + this.user?.photo
        return img
      }
    }
  },
  watch: {},
  created () {
    this.loadUser()
  },
  onShow () {
    this.loadUser()
  },
  mounted () {},
  methods: {
    // 修改用户资料
    async onUpdataUser () {
      this.updataProfileLoading = true
      const { name, intro, email } = this.user
      await upadataUserprofile({
        name,
        intro,
        email
      })
      this.$message({
        type: 'success',
        message: '保存成功'
      })
      this.updataProfileLoading = false
      gloobalBus.$emit('updata-user', this.user)
    },
    async loadUser () {
      const res = await getUserProfile()
      this.user = res.data.data
    },
    onFileChange () {
      // 处理图片预览
      const file = this.$refs.file
      // 将图片对象设置为图片的src
      const blobData = window.URL.createObjectURL(file.files[0])
      this.priviewImage = blobData
      // 展示弹出层，预览用户选择的图片
      this.dialogVisible = true
      // 解决选择相同文件不触发change事件问题
      this.$refs.file.value = ''
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    onDialogOpen () {
      this.uploadPhotoLoading = false
      // 获取图片dom
      // 图片裁切器必须基于img进行初始化,注意，img必须是可见状态才能正常运行初始化,
      // 因为我们这里要在对话框里面初始化裁切器，所以务必要在对话框完全打开的状态去进行初始化
      // const image = document.getElementById('image');
      const image = this.$refs['preview-image']
      // 第一次初始化，图片发生变化，裁切器不会更新，
      // 方法一：裁切器.replace方法
      // 方法二：销毁裁切器，重新初始化
      this.cropper = new Cropper(image, {
        // aspectRatio: 16 / 9,
        aspectRatio: 1,
        viewMode: 1,
        dragMode: 'none',
        cropBoxResizable: false
        // crop (event) {
        //   console.log(event.detail.x)
        //   console.log(event.detail.y)
        //   console.log(event.detail.width)
        //   console.log(event.detail.height)
        //   console.log(event.detail.rotate)
        //   console.log(event.detail.scaleX)
        //   console.log(event.detail.scaleY)
        // }
      })
    },
    onDialogClose () {
      // 对话框关闭，销毁裁切器,或者用.replace也可以实现
      this.cropper.destroy()
    },

    onUpdataPhoto () {
      this.uploadPhotoLoading = true
      // 获取裁切的图片对象
      this.cropper.getCroppedCanvas().toBlob(async file => {
        const fd = await new Promise((resolve, reject) => {
          readFileImg(file, resolve, reject)
        })
        // const fd = new FormData()
        // fd.append('photo', this.formData)
        // 请求更新用户头像
        await updataUserPhoto(fd)
        this.dialogVisible = false
        this.user.photo = window.URL.createObjectURL(file)
        gloobalBus.$emit('updata-user', this.user)
        // 把服务器端的图片返回展示有点慢
        // this.user.photo = res.data.data.photo
      })
      this.$message({
        type: 'success',
        message: '修改成功'
      })
      // 关闭对话框
      // setTimeout(() => {
      //   this.uploadPhotoLoading = false
      // }, 1000)
      // 更新视图展示
    }
  }
}
</script>

<style lang='less' scoped>
.preview-image-wrap {
  .preview-image {
    display: block;

    /* This rule is very important, please don't ignore this */
    max-width: 100%;
    height: 200px;
  }
}
.imgBox {
  width: 200px;
  height: 200px;
  margin-right: 5px;
  border: 2px solid #a7a7a7;
  padding: 2px;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  :first-child {
    border-radius: 8px;
  }
}
</style>
